package com.wugui.datax.admin.util;

import com.beust.jcommander.internal.Lists;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * MongoDb工具类
 */
public class MongoUtils {
    /**
     * 从mongodb的连接url中提取用户名和密码
     * @param url mongodb的连接url,格式为mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
     * @return 如果有用户名密码串，返回用户名密码的list，如果没有匹配，返回空list
     */
    public static List<String> getMongoUsernamePasswordFromUrl(String url){
        String regex = "^mongodb://(\\S+):(\\S+)@";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(url);
        if(matcher.find()){
            String username = matcher.group(1);
            String pwd = matcher.group(2);
            return Lists.newArrayList(username, pwd);
        }
        return Lists.newArrayList();
    }

    public static void main(String[] args){
        String url = "mongodb://ab_1c:ddafa$aaf@192.168.1.101:27017,192.168.1.102:27017,192.168.1.103:27017/?authSource=test";
//        String url = "mongodb://192.168.1.101:27017,192.168.1.102:27017,192.168.1.103:27017/?authSource=test";
        List<String> list = getMongoUsernamePasswordFromUrl(url);
        System.out.println(list);
    }
}
